package com.unitd.frame.comm.utils;

import com.unitd.frame.comm.utils.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @desc ip 工具类
 * @filename IpUtils.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2016/11/13
 */
public class IpUtils {

	/**
	 * @desc 判断是否为内网IP地址
	 * @param ipAddr ip地址信息
	 * @return boolean
	 */
	public static boolean isInnerIp(String ipAddr) {
		if (StringUtils.isBlank(ipAddr)) return false;
		return ipAddr.startsWith("127") || ipAddr.startsWith("192.168") || ipAddr.startsWith("10.");
	}

	/**
	 * @desc 获取客户端的IP地址信息, 通过 request.getRemoteAddr(),这种方法在大部分情况下都是有效的.
	 * 但是在通过了Apache,Squid等反向代理软件就不能获取到客户端的真实IP地址了,如果通过了多级反向代理的话,
	 * X-Forwarded-For的值并不止一个,而是一串IP值, 究竟哪个才是真正的用户端的真实IP呢？
	 * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串.
	 * 例如：X-Forwarded-For：192.168.1.110, 192.168.1.120,
	 * 192.168.1.130, 192.168.1.100 用户真实IP为： 192.168.1.110
	 * @param request http请求
	 * @return IP地址信息
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		// 检查以localhost, 127.0.0.1访问时得到真实IP
		ip = checkLocalIp(ip);

		if (ip != null && ip.indexOf(",") > 0) {
			ip = ip.substring(0, ip.indexOf(","));
		}
		return ip;
	}

	/**
	 * @desc 检查以localhost, 127.0.0.1访问时得到真实IP
	 * @param ip ip地址
	 * @return 实际IP地址
	 */
	public static String checkLocalIp(String ip) {
		if ("0:0:0:0:0:0:0:1".equals(ip) || "127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1%0".equals(ip)) {
			try {
				// 根据网卡取本机配置的IP
				InetAddress inetAddress = InetAddress.getLocalHost();
				ip = inetAddress.getHostAddress();

				// 对于通过多个代理的情况, 第一个IP为客户端真实IP,多个IP按照','分割 "***.***.***.***".length() = 15
				if (ip != null && ip.length() > 15) { //"***.***.***.***".length() = 15
					if (ip.indexOf(",") > 0) {
						ip = ip.substring(0, ip.indexOf(","));
					}
				}
//				System.out.println("当前发起请求的客户端IP地址:" +ip);
			} catch (UnknownHostException e) {
				e.printStackTrace();
			}
		}
		return ip;
	}
}